/**
 * 全局状态管理
 * pinia: https://pinia.vuejs.org/
 */
import { defineStore } from "pinia";
import { ref, computed } from "vue";
import { request } from "@/components/apis";
import { useTodosStore } from "./todos";

import { User } from "@/components/types";

export const useUserStore = defineStore("main", () => {
  let loading = false;
  const user = ref<User>(),
    todosStore = useTodosStore(),
    login = (payload: User) => {
      user.value = payload;
      todosStore.reset();
      todosStore.load();
    },
    logout = () => {
      user.value = undefined;
      todosStore.reset();
    },
    getUserInfo = async () => {
      if (user.value || loading) return;
      // 获取服务器用户登录信息
      try {
        loading = true;
        const { data } = await request<User>("/profile", {
          ignoreNotifyError: true,
        });
        if (data.success && data.object) login(data.object);
      } finally {
        loading = false;
      }
    },
    isAuth = computed(() => user.value != undefined),
    avatar = computed(() =>
      user.value?.avatar
        ? `/avatars/${user.value.avatar}`
        : `/avatar/${user.value?.nickname}`
    );
  // once
  // getUserInfo();
  return {
    user,
    login,
    logout,
    isAuth,
    avatar,
    getUserInfo,
  };
});
